package com.ls.shiroWithJwt.controller;

import com.ls.shiroWithJwt.constant.Constants;
import com.ls.shiroWithJwt.entity.UserEntity;
import com.ls.shiroWithJwt.shiro.token.JwtAuthenticationToken;
import com.ls.shiroWithJwt.utils.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 登陆相关控制器
 */
@RestController
public class LoginController {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @RequestMapping(value = "/login",method = {RequestMethod.POST,RequestMethod.GET})
    public Map<String,Object> login(@RequestParam String userName,@RequestParam String password){
        Map<String,Object> resultMap = new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        try{
            JwtAuthenticationToken token = new JwtAuthenticationToken(userName, password);
            subject.login(token);
        }catch (Exception e) {
            LOGGER.error("登陆出错:" + e.getMessage());
            resultMap.put("success", false);
            resultMap.put("message", "登陆出错:" + e.getMessage());
            return resultMap;
        }
        UserEntity userAccountInfo = (UserEntity) subject.getPrincipal();

        Map<String,String> claims = new HashMap<>();
        //此处按照自己的业务放入合适的数据
        claims.put(Constants.DEFAULT_PRINCIPAL,userName);
        claims.put("realName",userAccountInfo.getRealName());
        claims.put("userId",userAccountInfo.getId().toString());

        try {
            String token = JwtUtil.createToken(claims);
            resultMap.put("success", true);
            resultMap.put("token", token);
            return resultMap;
        } catch (Exception e) {
            LOGGER.error("生成token出错",e);
            resultMap.put("success", false);
            resultMap.put("message", "登陆出错:" + e.getMessage());
            return resultMap;
        }
    }

    /**
     * 退出登陆
     * @return
     */
    @PostMapping("/logout")
    public void logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }

}
